package com.yunshan.mp;

import com.yunshan.common.core.controller.BaseController;
import com.yunshan.common.core.domain.AjaxResult;
import com.yunshan.common.utils.UserUtils;
import com.yunshan.member.domain.MemberSubCardInfo;
import com.yunshan.member.domain.MemberUserInfo;
import com.yunshan.member.service.IMemberSubCardInfoService;
import com.yunshan.member.service.IMemberUserInfoService;
import com.yunshan.wechat.domain.WechatUserInfo;
import com.yunshan.wechat.service.IWechatUserInfoService;
import com.yunshan.welfare.domain.*;
import com.yunshan.welfare.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 会员权益信息
 *
 * @author yunshan
 * @date 2025-03-25
 */
@Api(tags = "会员权益信息")
@RestController
@RequestMapping("/wx/welfare")
public class WelfareController extends BaseController {

    @Autowired
    private IWelfareGiftRecordService welfareGiftRecordService;
    @Autowired
    private IWelfareGiftService welfareGiftService;
    @Autowired
    private IWelfareCouponRecordService welfareCouponRecordService;
    @Autowired
    private IWechatUserInfoService wechatUserInfoService;
    @Autowired
    private IMemberUserInfoService memberUserInfoService;
    @Autowired
    private IMemberSubCardInfoService memberSubCardInfoService;
    @Autowired
    private IWelfareCouponService welfareCouponService;
    @Autowired
    private IWelfareGiftContentService welfareGiftContentService;

    @ApiOperation("获取我的礼包")
    @GetMapping("getGift")
    private AjaxResult getGift() {
        try {
            Long userId = UserUtils.getUserId();
            if (userId == null) {
                return error("用户登录异常");
            }
            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
            if (wechatUserInfo == null) {
                return error("用户信息异常");
            }

            Long memberId;
            //查询会员信息
            if (wechatUserInfo.getType() == 1){
                memberId = memberUserInfoService.selectUserInfoByUserId(userId).getId();

            }else {
                MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByUserId(userId);
                memberId = memberUserInfoService.selectMemberUserInfoById(memberSubCardInfo.getMemberId()).getId();
            }

            //查询礼包
            WelfareGiftRecord welfareGiftRecord = new WelfareGiftRecord();
            welfareGiftRecord.setMemberId(memberId);
            List<WelfareGiftRecord> giftRecords = welfareGiftRecordService.selectWelfareGiftRecordListGroup(welfareGiftRecord);

            List<WelfareGift> welfareGifts = new ArrayList<>();

            //查询礼包内容
            if (giftRecords.size() > 0) {
                for (WelfareGiftRecord giftRecord : giftRecords) {
                    welfareGiftRecord.setGiftId(giftRecord.getGiftId());
                    welfareGiftRecord.setCreateTime(giftRecord.getCreateTime());
                    List<WelfareGiftRecord> welfareGiftRecords = welfareGiftRecordService.selectUniWelfareGiftRecord(welfareGiftRecord);

                    if (welfareGiftRecords.size() > 0) {
                        WelfareGift welfareGift = welfareGiftService.selectWelfareGiftById(welfareGiftRecords.get(0).getGiftId());
                        welfareGift.setEndTime(welfareGiftRecords.get(0).getEndTime());
                        welfareGift.setWelfareGiftRecords(welfareGiftRecords);
                        welfareGift.setStatus(giftRecord.getStatus());
                        welfareGifts.add(welfareGift);
                    }
                }

            }

            return success(welfareGifts);

        } catch (Exception e){
            return error(e.getMessage());
        }
    }

    @ApiOperation("获取我的礼包详情")
    @GetMapping("getGiftInfo")
    private AjaxResult getGiftInfo(
            @ApiParam(name = "id", value = "礼包id", required = true)
            @RequestParam Long id) {
        try {
            Long userId = UserUtils.getUserId();
            if (userId == null) {
                return error("用户登录异常");
            }
            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
            if (wechatUserInfo == null) {
                return error("用户信息异常");
            }

            //查询详情
            WelfareGiftRecord welfareGiftRecord = welfareGiftRecordService.selectWelfareGiftRecordById(id);
            if (welfareGiftRecord != null) {
                //查询优惠券
                WelfareGiftContent welfareGiftContent = welfareGiftContentService.selectWelfareGiftContentById(welfareGiftRecord.getGiftContentId());
                WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(welfareGiftContent.getContentId());
                welfareCoupon.setEndTime(welfareGiftRecord.getEndTime());
                welfareCoupon.setId(welfareGiftRecord.getId());

                //优惠券数量
                welfareGiftRecord.setStatus(0);

                List<WelfareGiftRecord> welfareGiftRecords = welfareGiftRecordService.selectUniWelfareGiftRecord(welfareGiftRecord);
                if (welfareGiftRecords.size() == 0) {
                    welfareGiftRecord.setStatus(null);
                    welfareGiftRecord.setGiftContentId(null);
                    welfareGiftRecords = welfareGiftRecordService.selectUniWelfareGiftRecord(welfareGiftRecord);
                }

                for (WelfareGiftRecord giftRecord : welfareGiftRecords) {
                    if (giftRecord.getGiftContentId().equals(welfareGiftContent.getId())) {
                        welfareCoupon.setStatus(giftRecord.getStatus());
                        welfareCoupon.setSunNum(giftRecord.getSunNum());
                        welfareCoupon.setUseNum(giftRecord.getUseNum());
                    }
                }

                return success(welfareCoupon);
            }

        } catch (Exception e){
            return error(e.getMessage());
        }
        return success();
    }

    @ApiOperation("获取优惠券")
    @GetMapping("getCoupon")
    private AjaxResult getCoupon(
            @ApiParam(name = "status", value = "使用状态 0:待使用  1:已核销  2：已取消 ", required = true)
            @RequestParam Integer status) {
        try {
            Long userId = UserUtils.getUserId();
            if (userId == null) {
                return error("用户登录异常");
            }
            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
            if (wechatUserInfo == null) {
                return error("用户信息异常");
            }

            WelfareCouponRecord welfareCouponRecord = new WelfareCouponRecord();

            //主卡or副卡
            Long memberId;
            if (wechatUserInfo.getType() == 1) {
                memberId = memberUserInfoService.selectUserInfoByUserId(userId).getId();
            }else{
                MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByUserId(userId);
                memberId = memberUserInfoService.selectMemberUserInfoById(memberSubCardInfo.getMemberId()).getId();
            }
            welfareCouponRecord.setMemberId(memberId);
            welfareCouponRecord.setStatus(status);

            //副卡非待使用状态的优惠券
            if (wechatUserInfo.getType() == 2 && status != 0){
                return success(welfareCouponRecordService.selectWelfareCouponRecordQuery(welfareCouponRecord));
            }

            return success(welfareCouponRecordService.selectWelfareCouponRecordQuery(welfareCouponRecord));

        } catch (Exception e){
            return error(e.getMessage());
        }

    }

    @ApiOperation("获取优惠券详情")
    @GetMapping("getCouponInfo")
    private AjaxResult getCouponInfo(
            @ApiParam(name = "id", value = "优惠券id", required = true)
            @RequestParam Long id) {
        try {
            Long userId = UserUtils.getUserId();
            if (userId == null) {
                return error("用户登录异常");
            }
            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
            if (wechatUserInfo == null) {
                return error("用户信息异常");
            }

            WelfareCouponRecord welfareCouponRecord = welfareCouponRecordService.selectWelfareCouponRecordById(id);

            if (welfareCouponRecord != null){
                WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(welfareCouponRecord.getCouponId());
                welfareCoupon.setEndTime(welfareCouponRecord.getEndTime());
                welfareCoupon.setId(welfareCouponRecord.getId());
                welfareCoupon.setStatus(welfareCouponRecord.getStatus());
                return success(welfareCoupon);
            }
            return success();

        } catch (Exception e){
            return error(e.getMessage());
        }

    }


    @ApiOperation("转增优惠券")
    @PostMapping("giveCoupon")
    private AjaxResult giveCoupon(
            @RequestBody Map<String,String> map){
        try {

            Long id = Long.parseLong(map.get("id"));
            Long userId = Long.parseLong(map.get("userId"));

            WelfareCouponRecord welfareCouponRecord = welfareCouponRecordService.selectWelfareCouponRecordById(id);
            if (welfareCouponRecord == null) {
                return error("优惠券不存在");
            } else if (welfareCouponRecord.getStatus() != 0) {
                return error("优惠券已使用或已过期");
            }

            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
            if (wechatUserInfo == null) {
                return error("转增用户异常，请重试");
            }
            MemberUserInfo memberUserInfo = memberUserInfoService.selectUserInfoByUserId(wechatUserInfo.getId());
            if (memberUserInfo == null) {
                return error("非主卡用户不可转增");
            }

            //判断转增用户和优惠券绑定用户是否一个
            if (!memberUserInfo.getId().equals(welfareCouponRecord.getMemberId())) {
                return error("该优惠券已被领取");
            }

            WelfareCouponRecord couponRecord = new WelfareCouponRecord();
            couponRecord.setId(welfareCouponRecord.getId());

            //被转赠用户
            WechatUserInfo wechatUser = wechatUserInfoService.selectWechatUserInfoById(UserUtils.getUserId());
            if (wechatUser != null) {
                if (wechatUserInfo.getId().equals(wechatUser.getId())){
                    return error("不能领取自己转增的优惠券");
                }

                //主卡用户
                if (wechatUser.getType() == 1) {
                    MemberUserInfo memberUser = memberUserInfoService.selectUserInfoByUserId(wechatUser.getId());
                    couponRecord.setMemberId(memberUser.getId());
                } else {
                    MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByUserId(wechatUser.getId());

                    if (memberSubCardInfo.getMemberId().equals(memberUserInfo.getId())){
                        return error("已是副卡用户，可直接使用");
                    }

                    couponRecord.setMemberId(memberUserInfoService.selectMemberUserInfoById(memberSubCardInfo.getMemberId()).getId());
                }
            }

            return success(welfareCouponRecordService.updateWelfareCouponRecord(couponRecord));
        }catch (Exception e){
            return error("领取失败，请重试");
        }
    }
}
